package com.siau.SevenBubble;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.google.gson.Gson;
import com.igexin.sdk.GTIntentService;
import com.igexin.sdk.message.GTCmdMessage;
import com.igexin.sdk.message.GTNotificationMessage;
import com.igexin.sdk.message.GTTransmitMessage;

import java.io.UnsupportedEncodingException;

import hhm.android.library.LogUtils;
import hhm.android.library.utils.OnMultiClickListener;
import hhm.android.main.MainActivity;
import hhm.android.main.WebViewActivity;
import hhm.android.my.FriendListActivity;
import hhm.android.my.MyBabyListActivity;
import siau.android.base.AdActivityDialog;
import siau.android.base.BlueToothUtil;
import siau.android.base.HttpHelper;
import siau.android.base.MyBlueToothBean;
import siau.android.base.SBApplication;
import siau.android.base.SystemUtil;
import siau.android.http.model.AdvertisementModel;
import siau.android.http.model.CidRequest;
import siau.android.http.model.ClickPushMessageRequest;
import siau.android.http.model.EventPushModel;
import siau.android.http.model.NotifyPushModel;
import siau.android.library.KeyString;

import static siau.android.base.DialogUtilsKt.getAdDialog;

/**
 * 继承 GTIntentService 接收来自个推的消息，所有消息在线程中回调，如果注册了该服务，则务必要在 AndroidManifest 中声明，否则无法接受消息
 */
public class SBIntentService extends GTIntentService {

    @Override
    public void onReceiveServicePid(Context context, int pid) {
    }

    // 处理透传消息
    @Override
    public void onReceiveMessageData(Context context, GTTransmitMessage msg) {
        // 透传消息的处理，详看 SDK demo

        if (TextUtils.isEmpty(KeyString.token)) {
            return;
        }

        String message = new String(msg.getPayload());
        LogUtils.Companion.e("hhm--> push  ", message);
        if (message.contains("pushEventType")) {
            EventPushModel eventPushModel = new Gson().fromJson(message, EventPushModel.class);
            switch (eventPushModel.getPushEventType()) {
                case 1:
                    new HttpHelper().getDefaultFamily().subscribe(o -> {
                        SBApplication.userData = o;
                        if (isTopActivitySome("MyBabyListActivity")) {
                            SBApplication.Companion.setBecomeCreator(true);
                            Intent intent = new Intent(context, MyBabyListActivity.class);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intent.putExtra(KeyString.type, KeyString.becomeCreator);
                            startActivity(intent);
                        } else if (isTopActivitySome("FriendListActivity")) {
                            SBApplication.Companion.setBecomeCreator(true);
                            Intent intent = new Intent(context, FriendListActivity.class);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intent.putExtra(KeyString.type, KeyString.becomeCreator);
                            startActivity(intent);
                        } else if (isTopActivity()) {
                            Intent intent = new Intent(context, MainActivity.class);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intent.putExtra(KeyString.type, KeyString.becomeCreator);
                            startActivity(intent);
                        } else {
                            SBApplication.Companion.setBecomeCreator(true);
                        }
                    }, throwable -> {
                    });
                    break;
                case 2:
                    new HttpHelper().getBindDeviceList().subscribe(o -> {
                        SBApplication.userData.setDeviceList(o);
                        for (int i = SBApplication.Companion.getBlueToothUtils().getConnectDevice().size(); i > 0; i--) {
                            MyBlueToothBean bindBean = SBApplication.Companion.getBlueToothUtils().getConnectDevice().get(i - 1);
                            boolean has = false;
                            for (int j = 0; j < o.size(); j++) {
                                if (bindBean.getBluetoothCode().equals(o.get(j).getBluetoothCode())) {
                                    has = true;
                                }
                            }
                            if (!has) {
                                SBApplication.Companion.getBlueToothUtils().disConnect(bindBean);
                                SBApplication.Companion.getBlueToothUtils().getConnectDevice().remove(bindBean);
                                SBApplication.Companion.getBlueToothUtils().connectDeviceNum.setValue(SBApplication.Companion.getBlueToothUtils().getConnectDevice().size());
                            }
                        }

                        if (isTopActivity()) {
                            Intent intent = new Intent(context, MainActivity.class);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intent.putExtra(KeyString.type, KeyString.refreshMainDevice);
                            startActivity(intent);
                        } else {
                            SBApplication.Companion.setRefreshMainActivityUI(true);
                        }
                    }, throwable -> {
                    });
                    break;
                case 3:
                    SBApplication.instance.homeless();
                    break;
                case 4:
                    new HttpHelper().getDefaultFamily().subscribe(o -> {
                        SBApplication.userData = o;
                        SBApplication.instance.openOtherFamily();
                    }, throwable -> {
                    });
                    break;
                case 6:
                    //先置空防止后面调接口
                    KeyString.token = "";
                    SBApplication.Companion.sendOnePointReceiver(true);
                    break;
            }
        } else if (message.contains("notifyType")) {
            NotifyPushModel notifyPushModel = new Gson().fromJson(message, NotifyPushModel.class);

            try {
                if (SBApplication.userData != null && SBApplication.userData.getUserStatus() == 1 && !TextUtils.isEmpty(KeyString.token)) {

                    ClickPushMessageRequest b = new ClickPushMessageRequest(notifyPushModel.getNotifyId(), SystemUtil.getSystemModel(), notifyPushModel.getNotifyType());
                    new HttpHelper().clickPushMessage(b).subscribe(o -> {
                    }, throwable -> {
                    });

                    if (notifyPushModel.getNotifyType() == 4 && !TextUtils.isEmpty(notifyPushModel.getNotifyLink())) {
                        Intent intent = new Intent(context, WebViewActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.putExtra(KeyString.url, notifyPushModel.getNotifyLink());
                        startActivity(intent);
                    } else if (notifyPushModel.getNotifyType() == 5 && notifyPushModel.getAdvert() != null) {
                        AdvertisementModel ad = new AdvertisementModel(notifyPushModel.getAdvert().getImageUrl(), notifyPushModel.getAdvert().getSkipPath(), "" + notifyPushModel.getAdvert().getAdvertId(), notifyPushModel.getAdvert().getSkipType(), 0);

                        Intent intent = new Intent(context, AdActivityDialog.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.putExtra(KeyString.data, ad);
                        startActivity(intent);
                    } else {
                        Intent intent = new Intent(context, MainActivity.class);
                        intent.putExtra(KeyString.isMainTop, isTopActivity());
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.putExtra(KeyString.type, KeyString.pushMessage);
                        startActivity(intent);
                    }
                } else {
                    Intent intent = new Intent(context, SplashActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK & Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }
            } catch (Exception e) {
                Intent intent = new Intent(context, SplashActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK & Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        }
    }

    /**
     * 判断当前MainActivity是否在最顶层 (被别的页面挡住或者不在桌面都为false 只有打开首页并且显示才为true)
     *
     * @return
     */
    private boolean isTopActivity() {
        boolean isTop = false;
        ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        if (cn.getClassName().contains("MainActivity")) {
            isTop = true;
        }
        return isTop;
    }

    /**
     * 判断某个MainActivity是否在最顶层 (被别的页面挡住或者不在桌面都为false 只有打开首页并且显示才为true)
     *
     * @return
     */
    private boolean isTopActivitySome(String activityName) {
        boolean isTop = false;
        ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        if (cn.getClassName().contains(activityName)) {
            isTop = true;
        }
        return isTop;
    }

    // 接收 cid
    @Override
    public void onReceiveClientId(Context context, String clientid) {
        LogUtils.Companion.e("hhm-clientid", clientid);
        SBApplication.Companion.setCid(clientid);
    }

    // cid 离线上线通知
    @Override
    public void onReceiveOnlineState(Context context, boolean online) {
    }

    // 各种事件处理回执
    @Override
    public void onReceiveCommandResult(Context context, GTCmdMessage cmdMessage) {
    }

    // 通知到达，只有个推通道下发的通知会回调此方法
    @Override
    public void onNotificationMessageArrived(Context context, GTNotificationMessage msg) {
    }

    // 通知点击，只有个推通道下发的通知会回调此方法
    @Override
    public void onNotificationMessageClicked(Context context, GTNotificationMessage msg) {
    }
}